/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.browser;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.util.QueryInfo;
import com.blandware.atleap.model.core.Page;
import com.blandware.atleap.service.core.PageManager;
import com.blandware.atleap.webapp.taglib.core.grid.util.Grid;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * <p>Returns browser page with allows to select a linkable item
 * </p>
 * <p><a href="BrowseLinkableItemsAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.17 $ $Date: 2007/12/19 12:49:49 $
 * @struts.action path="/core/browser/browseLinkableItems"
 * validate="false"
 * roles="core-browser-linkableItems"
 * @struts.action-forward name="showBrowser"
 * path=".core.browser.linkableItemsBrowser"
 */
public final class BrowseLinkableItemsAction extends BaseBrowserAction {

	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        HttpSession session = request.getSession();

        boolean opening = getOpening(request);
        String modeToRequest = WebappConstants.BROWSER_MODE_LINKS;
        if (!GenericValidator.isBlankOrNull(request.getParameter("mode"))) {
            modeToRequest = request.getParameter("mode");
        }
        String mode = processOpeningAndGetMode(opening, session,
                                               modeToRequest, WebappConstants.BROWSER_MODE_LINKS);

        // computing name of menu
        computeMenuNameAndSaveToRequest(mode, request);

		// check for locale suffix
		String localeSuffix;
        if ( !GenericValidator.isBlankOrNull(request.getParameter("editorAreaLanguage")) ) {
			localeSuffix = request.getParameter("editorAreaLanguage");
			session.setAttribute(WebappConstants.BROWSER_LOCALE_SUFFIX_KEY, localeSuffix);
		} else {
			localeSuffix = (String) session.getAttribute(WebappConstants.BROWSER_LOCALE_SUFFIX_KEY);
		}

		Grid liGrid = getGridByName(WebappConstants.BROWSER_LINKABLE_ITEMS_GRID, session);
		if ( liGrid == null ) {
			liGrid = new Grid(WebappConstants.BROWSER_LINKABLE_ITEMS_GRID);
		}

		saveGrid(liGrid, session);

		QueryInfo queryInfo = new QueryInfo();
		queryInfo.setWhereClause(liGrid.getWhereClause());

		Map queryParameters = new HashMap();
		Locale locale = (Locale) session.getAttribute(Globals.LOCALE_KEY);
		queryParameters.put("localeIdentifier", locale.getLanguage());
		queryInfo.setQueryParameters(queryParameters);

		PageManager pageManager = (PageManager) getBean(Constants.PAGE_MANAGER_BEAN);
		List linkableItems = pageManager.listLinkableItems(queryInfo).asList();

		for ( ListIterator i = linkableItems.listIterator(); i.hasNext(); ) {
			Page linkableItem = (Page) i.next();
			Page newItem = new Page() {
			};
			WebappUtil.copyProperties(newItem, linkableItem, request);
			String uri = WebappUtil.getActionMappingURL(linkableItem.getUri(), null, request, WebappConstants.URL_TYPE_CONTEXT_RELATIVE, localeSuffix);
			if ( uri.startsWith("/") ) {
				uri = uri.substring(1);
			}
			newItem.setUri(uri);
			i.set(newItem);
		}

		request.setAttribute(WebappConstants.BROWSER_LINKABLE_ITEMS_COLLECTION_KEY, linkableItems);

		return mapping.findForward("showBrowser");
	}
}